# coding:utf-8
import streamlit as st
import requests
import json

# 高德 API 配置
AMAP_KEY = " "  # 替换为你的高德 API Key
GEOCODE_URL = "https://restapi.amap.com/v3/geocode/geo"
TRANSIT_URL = "https://restapi.amap.com/v5/direction/transit/integrated"
DISTRICT_URL = "https://restapi.amap.com/v3/config/district"

def get_citycode(city_name):
    """根据城市名称获取 citycode"""
    params = {
        "key": AMAP_KEY,
        "keywords": city_name,
        "subdistrict": 2
    }
    try:
        response = requests.get(DISTRICT_URL, params=params)
        data = response.json()
        if data["status"] == "1" and len(data["districts"]) > 0:
            return data["districts"][0].get("citycode", "010")  # 默认北京 010
        return "010"
    except Exception as e:
        st.error(f"获取城市编码失败: {e}")
        return "010"

def geocode_address(address):
    """将地址转换为经纬度"""
    params = {
        "key": AMAP_KEY,
        "address": address,
    }
    try:
        response = requests.get(GEOCODE_URL, params=params)
        data = response.json()
        if data["status"] == "1" and len(data["geocodes"]) > 0:
            location = data["geocodes"][0]["location"]
            return tuple(map(float, location.split(',')))
        return None
    except Exception as e:
        st.error(f"地址解析失败: {str(e)}")
        return None

def get_transit_plan(origin, destination, city):
    """获取公交路线规划"""
    params = {
        "key": AMAP_KEY,
        "origin": f"{origin[0]},{origin[1]}",
        "destination": f"{destination[0]},{destination[1]}",
        "city1": city,
        "city2": city,
        # "strategy": 3,
        "AlternativeRoute": 1
    }
    try:
        response = requests.get(TRANSIT_URL, params=params)
        return response.json()
    except Exception as e:
        st.error(f"API请求失败: {str(e)}")
        return None


# def parse_transit_routes(route_data):
#     """解析公交路线数据，展示公交和步行信息"""
#     route_info = []
#
#     # 直接遍历顶层的路线方案列表
#     if isinstance(route_data, list):
#         for idx, transit in enumerate(route_data):
#             segments = []
#             # 提取每个方案的 segments
#             for segment in transit.get("segments", []):
#                 # 处理步行段
#                 if "walking" in segment:
#                     walking = segment["walking"]
#                     walk_distance = walking.get("distance", "0")
#                     steps = walking.get("steps", [])
#                     step_instructions = " → ".join(
#                         [step.get("instruction", "") for step in steps]
#                     )
#                     segments.append(f"🚶 步行 {walk_distance}米 ({step_instructions})")
#
#                 # 处理公交段（包括地铁）
#                 elif "bus" in segment:
#                     bus = segment["bus"]
#                     for busline in bus.get("buslines", []):
#                         # 判断交通类型
#                         transport_type = busline.get("type", "")
#                         icon = "🚌"  # 默认公交
#                         if "地铁" in transport_type:
#                             icon = "🚇"
#
#                         # 处理出发站名称（含入口）
#                         departure_stop = busline.get("departure_stop", {})
#                         departure_name = departure_stop.get("name", "")
#                         if "entrance" in departure_stop:
#                             entrance = departure_stop["entrance"].get("name", "")
#                             departure_name += f" ({entrance})"
#
#                         # 处理到达站名称（含出口）
#                         arrival_stop = busline.get("arrival_stop", {})
#                         arrival_name = arrival_stop.get("name", "")
#                         if "exit" in arrival_stop:
#                             exit = arrival_stop["exit"].get("name", "")
#                             arrival_name += f" ({exit})"
#
#                         # 拼接线路信息
#                         bus_name = busline.get("name", "")
#                         segments.append(f"{icon} {bus_name}（{departure_name} ➝ {arrival_name}）")
#
#             if segments:
#                 route_info.append({
#                     "方案": f"方案 {idx + 1}",
#                     "路线详情": " → ".join(segments),
#                     "总距离": transit.get("distance", "0"),
#                     "步行距离": transit.get("walking_distance", "0")
#                 })
#
#     return route_info


# Streamlit 界面
def parse_transit_routes(route_data):
    """解析公交、地铁、步行等路线信息"""
    route_info = []

    # 遍历所有的出行方案
    for idx, transit in enumerate(route_data):
        segments = []

        # 遍历各个路段（步行、公交、地铁、出租车）
        for segment in transit.get("segments", []):

            # 处理步行段
            if "walking" in segment:
                walking = segment["walking"]
                walk_distance = walking.get("distance", "0")
                steps = walking.get("steps", [])
                step_instructions = " → ".join(
                    [step.get("instruction", "") for step in steps]
                )
                segments.append(f"🚶 步行 {walk_distance} 米 ({step_instructions})")

            # 处理公交或地铁
            if "bus" in segment:
                bus = segment["bus"]
                for busline in bus.get("buslines", []):
                    transport_type = busline.get("type", "")
                    icon = "🚌" if "公交" in transport_type else "🚇"  # 区分地铁与公交

                    # 出发站信息
                    departure_stop = busline.get("departure_stop", {})
                    departure_name = departure_stop.get("name", "")
                    entrance = departure_stop.get("entrance", {}).get("name", "")
                    if entrance:
                        departure_name += f" ({entrance})"

                    # 到达站信息
                    arrival_stop = busline.get("arrival_stop", {})
                    arrival_name = arrival_stop.get("name", "")
                    exit = arrival_stop.get("exit", {}).get("name", "")
                    if exit:
                        arrival_name += f" ({exit})"

                    # 途经站点
                    via_stations = [
                        stop.get("name", "") for stop in busline.get("via_stops", [])
                    ]
                    via_text = f"经 {', '.join(via_stations)}" if via_stations else "直达"

                    # 线路信息
                    bus_name = busline.get("name", "")
                    segments.append(f"{icon} {bus_name}（{departure_name} ➝ {arrival_name}，{via_text}）")

            # 处理出租车（如有）
            if "taxi" in segment:
                taxi = segment["taxi"]
                start_name = taxi.get("startname", "未知地点")
                end_name = taxi.get("endname") or "目的地"
                price = taxi.get("price", "未知价格")
                segments.append(f"🚖 出租车 {start_name} ➝ {end_name}   预计 {price} 元")

        # 汇总每个方案的路线信息
        if segments:
            route_info.append({
                "方案": f"方案 {idx + 1}",
                "路线详情": " → ".join(segments),
                "总距离": f"{transit.get('distance', '0')} 米",
                "步行距离": f"{transit.get('walking_distance', '0')} 米"
            })

    return route_info


st.title("🚌 公交路线规划系统")
# origin_address = st.text_input("出发地", "合肥站")
# dest_address = st.text_input("目的地", "合肥骆岗公园")
# city_name = "合肥"
# city_code = get_citycode(city_name)  # 先获取 citycode
# origin = geocode_address(origin_address)
# destination = geocode_address(dest_address)
# plan_data = get_transit_plan(origin, destination, city_code)
# # 输入区域
col1, col2 = st.columns(2)
with col1:
    origin_address = st.text_input("出发地", "合肥站")
with col2:
    dest_address = st.text_input("目的地", "合肥骆岗公园")

city_name = st.text_input("输入目的城市：", "合肥")
# city_code = get_citycode("合肥")  # 先获取 citycode
# origin = geocode_address("合肥包公园")
# destination = geocode_address("合肥包公园")
# plan_data = get_transit_plan(origin, destination, city_code)
if st.button("开始规划"):
    with st.spinner("正在查询路线..."):
        city_code = get_citycode(city_name)  # 先获取 citycode
        origin = geocode_address(origin_address)
        destination = geocode_address(dest_address)

        if origin and destination:
            # 获取公交路线规划数据
            plan_data = get_transit_plan(origin, destination, city_code)
            if plan_data and plan_data.get("status") == "1":
                # 解析公交路线并以表格形式展示
                route_data = plan_data['route']['transits']
                print(route_data)
                transit_routes = parse_transit_routes(route_data)

                if transit_routes:
                    st.markdown("### 🚍 推荐公交路线")
                    st.table(transit_routes)
                else:
                    st.warning("未找到合适的公交路线")
            else:
                st.error("没有找到合适的公交路线")
        else:
            st.error("无法解析地址，请检查输入")

# 使用说明表格
st.markdown("### 🚀 使用指南")
instructions = [
    {"步骤": "1️⃣", "说明": "输入出发地和目的地地址"},
    {"步骤": "2️⃣", "说明": "输入目的城市"},
    {"步骤": "3️⃣", "说明": "点击「开始规划」按钮"},
    {"步骤": "4️⃣", "说明": "查看推荐的公交路线"}
]

st.table(instructions)
